﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using TjZheng.Framework;

namespace TjZheng.EasyUI
{
    public static partial class EasyUIExtension
    {
        /// <summary>
        /// RadioButton列表（空值验证）
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="name">input的name属性</param>
        /// <param name="value">input的value属性</param>
        /// <param name="isRequired">是否必选</param>
        /// <param name="selectList">RadioButton选项</param>
        /// <param name="htmlAttributes">Html属性</param>
        /// <returns></returns>
        public static MvcHtmlString RadioButtonList(this HtmlHelper htmlHelper, string name, object value, bool isRequired, List<SelectListItem> selectList, object htmlAttributes = null)
        {
            if (selectList.IsNull())
            {
                return MvcHtmlString.Create("<!--未设置RadioButton选项-->");
            }
            StringBuilder objStringBuilder = new StringBuilder();
            IDictionary<string, object> objHtmlAttributes = htmlAttributes.CreateValueDictionary();
            if (objHtmlAttributes.IsNull())
            {
                objHtmlAttributes = new Dictionary<string, object>();
            }
            string selector = name.Replace(".", "_");
            objHtmlAttributes["id"] = selector;
            objStringBuilder.AppendFormat("<div {0}>", objHtmlAttributes.Select(keyvalue => string.Format("{0}=\"{1}\"", keyvalue.Key, keyvalue.Value)).JoinString(" "));
            string valid = string.Format("class=\"easyui-validatebox\" data-options=\"validType:'validRadioButtonList[&quot;{0}&quot;]'\"", selector.FormatSelf("#{0}"));//双引号已经不能再用，所以用双引号的编码&quot;
            string objValue = value.ToString();
            if (objValue.IsNoNull())
            {
                foreach (var item in selectList)
                {
                    objStringBuilder.AppendFormat("<input type=\"radio\" name=\"{0}\" value=\"{1}\" {2} {3} />{4}", name, item.Value, string.Equals(objValue, item.Value, StringComparison.OrdinalIgnoreCase) ? "checked=\"checked\"" : "", isRequired ? valid : "", item.Text);
                }
            }
            else
            {
                foreach (var item in selectList)
                {
                    objStringBuilder.AppendFormat("<input type=\"radio\" name=\"{0}\" value=\"{1}\" {2} {3} />{4}", name, item.Value, item.Selected ? "checked=\"checked\"" : "", isRequired ? valid : "", item.Text);
                }
            }
            objStringBuilder.Append("</div>");
            return MvcHtmlString.Create(objStringBuilder.ToString());
        }
    }
}
